package org.example.controller;

import org.apache.http.client.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * 负载均衡测试
 * */
@RestController
@RequestMapping("/balance")
public class LoadBalanceController {

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    private RestTemplate restTemplate = new RestTemplate();

    @RequestMapping("/loadBalanceClient")
    public String loadBalanceClient() {

        //1. 获取服务
        ServiceInstance serviceInstance = loadBalancerClient.choose("eureka-product");

        //2. 根据服务拼接路径
        String url = String.format("http://%s:%s/product/test/i1",serviceInstance.getHost(),serviceInstance.getPort());

        //3. 使用 restTemplate 发送请求 todo 这里的 restTemplate 不能是带 @LoadBalance 的
        String res = restTemplate.getForObject(url, String.class);
        System.out.println("loadBalancerClient 调用结果：" + res);
        return res;
    }

}
